
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//import java.util.ArrayList;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import java.sql.ResultSet;

/*
 * JfrMain.java
 * Created on Oct 20, 2010, 6:34:38 PM
 * @author GTVT
 * @lastedit 23/4/2011
 */
public class JfrMain extends javax.swing.JFrame {

    /* Creates new form JfrMain */
    public JfrMain() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.metal.MetalLookAndFeel");
//            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

            // UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

        } catch (Exception e) {
        }
        initComponents();
        chkLog.doClick();
        url = new GiaVang();

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        spCount = new javax.swing.JSpinner();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        spTimeUpdate = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        cmdViewLog = new javax.swing.JButton();
        chkLog = new javax.swing.JCheckBox();
        jLabel4 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Tra Gia Vang Va Gia NGoai Te"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        addWindowStateListener(new java.awt.event.WindowStateListener() {
            public void windowStateChanged(java.awt.event.WindowEvent evt) {
                formWindowStateChanged(evt);
            }
        });

        jLabel1.setText("Số Lượng Hiển Thị");

        spCount.setValue(70);
        spCount.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spCountStateChanged(evt);
            }
        });

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Tỉ Giá Ngoại Tệ Nguồn NH-Ngoại Thương", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 1, 14))); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Tên Ngoại tệ", "Mua tiền mặt", "Mua chuyển khoản", "Bán"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setPreferredWidth(120);
        jTable2.getColumnModel().getColumn(1).setPreferredWidth(100);
        jTable2.getColumnModel().getColumn(2).setPreferredWidth(100);
        jTable2.getColumnModel().getColumn(3).setPreferredWidth(100);

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "NGUỒN CTY SJC VIỆT NAM", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Khu Vực", "Loại Vàng", "Giá Bán", "Giá Mua", "Thời Gian"
            }
        ));
        jTable1.setAutoscrolls(false);
        jTable1.setDragEnabled(true);
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Thời Gian Cập Nhật");

        spTimeUpdate.setValue(15);
        spTimeUpdate.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spTimeUpdateStateChanged(evt);
            }
        });

        jLabel3.setText("Phút");

        cmdViewLog.setText("View Log");
        cmdViewLog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdViewLogActionPerformed(evt);
            }
        });

        chkLog.setText("Log");
        chkLog.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                chkLogStateChanged(evt);
            }
        });
        chkLog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkLogActionPerformed(evt);
            }
        });

        jLabel4.setText("Listen Port:");

        txtPort.setText("2812");
        txtPort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPortActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(spCount, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(spTimeUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 487, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(50, 50, 50)
                        .addComponent(chkLog)
                        .addGap(18, 18, 18)
                        .addComponent(cmdViewLog)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(cmdViewLog)
                    .addComponent(chkLog))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addGap(480, 480, 480))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(spTimeUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(477, 477, 477))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addGap(480, 480, 480))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addGap(480, 480, 480))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(spCount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(477, 477, 477))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            // Cap nhat thong tin ve gia vang, dola
            this.getInfor();
            this.getInfor1();
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

        //Khoi dong 1 tieu trinh de tu dong
        //Cap nhat thong tin sau 1 khoang thoi gian
        threadCapNhat = new ThreadCapNhat(this, this.getTimeUpdate() * 1000 * 60);
        threadCapNhat.start();

        //Khoi dong tieu trinh de nhan cac yeu cau tu client
        try {
            server = new UDPSC(Integer.parseInt(txtPort.getText()));
        } catch (Exception e) {
            server = new UDPSC(2812);
            txtPort.setText("2812");
        }
        server.start();
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        threadCapNhat.done();
        server.stops();
    }//GEN-LAST:event_formWindowClosing

    private void spCountStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spCountStateChanged
        try {

            DbSqlite db = new DbSqlite("mydatabase.db");
            ResultSet rs = db.query("select count(*) from NGOAITE ");
            int countNT = Integer.parseInt(rs.getString(1));
            rs = db.query("select count(*) from GIAVANG");
            int countGV = Integer.parseInt(rs.getString(1));
            db.close();
            rs.close();

            if (countNT > this.getLimit()) {
                this.hienthiNT();
            }
            if (countGV > this.getLimit()) {
                this.hienthiGV();
            }


        } catch (Exception ex) {
        }
    }//GEN-LAST:event_spCountStateChanged

    private void spTimeUpdateStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spTimeUpdateStateChanged

        threadCapNhat.done();
        threadCapNhat = new ThreadCapNhat(this, this.getTimeUpdate() * 1000 * 60);
        threadCapNhat.start();

    }//GEN-LAST:event_spTimeUpdateStateChanged
    public class ShowWindow implements ActionListener {

        JfrMain hwnd;
        SystemTray myTray;
        TrayIcon trayIcon;

        public ShowWindow(JfrMain hwnd, SystemTray tray, TrayIcon trayIcon) {
            this.hwnd = hwnd;
            this.myTray = tray;
            this.trayIcon = trayIcon;
        }

        public void actionPerformed(ActionEvent e) {
            hwnd.setVisible(true);
            hwnd.setState(0);
            myTray.remove(trayIcon);
        }
    }

    public class CloseWindow implements ActionListener {

        JfrMain hwnd;

        public CloseWindow(JfrMain hwnd) {
            this.hwnd = hwnd;
        }

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }
    private void formWindowStateChanged(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowStateChanged
        if (this.getState() == 1) {//this means minimized
            if (SystemTray.isSupported()) {

                SystemTray tray = SystemTray.getSystemTray();
                Image image = Toolkit.getDefaultToolkit().getImage("icon.png");
                PopupMenu popup = new PopupMenu();
                MenuItem item = new MenuItem("Show");
                MenuItem item1 = new MenuItem("Close");

                popup.add(item);
                popup.add(item1);
                TrayIcon trayIcon = new TrayIcon(image, "Server Here", popup);
                item.addActionListener(new ShowWindow(this, tray, trayIcon));
                item1.addActionListener(new CloseWindow(this));
                try {
                    tray.add(trayIcon);
                    this.setVisible(false);
                } catch (AWTException e) {
                    System.err.println("Can't add to tray");
                }


            }
            /* }else if(this.getState()==0){//this means maximized/normal state

            }*/
    }//GEN-LAST:event_formWindowStateChanged
    }
        private void cmdViewLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdViewLogActionPerformed
            JDViewLogFile frmViewLog = new JDViewLogFile(this, true);
            frmViewLog.setVisible(true);
        }//GEN-LAST:event_cmdViewLogActionPerformed

        private void chkLogStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_chkLogStateChanged
        }//GEN-LAST:event_chkLogStateChanged

        private void chkLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkLogActionPerformed
            if (chkLog.isSelected()) {
                UDPSC.allowLog = true;
            } else {
                UDPSC.allowLog = false;
            }
        }//GEN-LAST:event_chkLogActionPerformed

        private void txtPortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPortActionPerformed

            server.stops();
            try {
                server = new UDPSC(Integer.parseInt(txtPort.getText()));
            } catch (Exception e) {
                server = new UDPSC(2812);
                txtPort.setText("2812");
            }
            server.start();

        }//GEN-LAST:event_txtPortActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JfrMain().setVisible(true);
            }
        });
    }

    /*
     * Cap nhat thong tin ve gia vang va hien thi
     */
    public void getInfor() throws Exception {

        //Cap nhat gia vang vao co so du lieu
        url.capnhatGiaVang();
        //Do du lieu vao Table va hien thi
        this.hienthiGV();

    }

    /*
     * Cap nhat thong tin ve ti gia
     * Hien thi du lieu NGOAITE o co so du lieu
     */
    public void getInfor1() {

        //Cap nhat ti gia hien tai vao co so du lieu
        try {
            TiGia.capnhat();
        } catch (Exception e) {
        }
        //Hien Thi Len Giao Dien
        this.hienthiNT();

    }

    public void hienthiGV() {
        try {
            DefaultTableModel mode = new javax.swing.table.DefaultTableModel(
                    new Object[][]{},
                    new String[]{
                        "Khu Vực", "Loại Vàng", "Giá Bán", "Giá Mua", "Thời Gian"
                    });
            jTable1.setModel(mode);
            String count = spCount.getValue().toString();
            //Ket noi, truy van gia vang tu csdl

            DbSqlite db = new DbSqlite("mydatabase.db");
            ResultSet rs = db.query("select * from GIAVANG order by THOIGIAN DESC limit " + count);
            //  sorter.setSortable(4, true);
            //Do ket qua vao Table va hien thi
            while (rs.next()) {
                mode.addRow(new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)});
            }
            db.close();
        } catch (Exception ex) {
        }
    }

    public void hienthiNT() {
        try {
            DefaultTableModel mode = new javax.swing.table.DefaultTableModel(
                    new Object[][]{},
                    new String[]{
                        "Ma", "Tên Ngoại tệ", "Mua tiền mặt", "Mua chuyển khoản", "Bán", "Thời Gian"
                    });
            jTable2.setModel(mode);

            String count = spCount.getValue().toString();
            //Lay Du Lieu Tu Co So Du Lieu
            DbSqlite db = new DbSqlite("mydatabase.db");
            ResultSet rs = db.query("select * from NGOAITE order by THOIGIAN DESC limit " + count);
            //Do ket qua vao Table va hien thi
            while (rs.next()) {
                mode.addRow(new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6)});
            }
        } catch (Exception ex) {
        }
    }

    private int getTimeUpdate() {
        return Integer.parseInt(spTimeUpdate.getValue().toString());
    }

    private int getLimit() {
        return Integer.parseInt(spCount.getValue().toString());
    }

    private int writeConfig() throws Exception {
        File file = new File("config.inf");
        FileOutputStream fos = new FileOutputStream(file);
        DataOutputStream dos = new DataOutputStream(fos);
        dos.writeChars("[config]\n");
        dos.writeChars("TimeUpdate:" + spTimeUpdate.toString());
        dos.writeChars("Log:" + chkLog.isSelected());

        return 0;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox chkLog;
    private javax.swing.JButton cmdViewLog;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JSpinner spCount;
    private javax.swing.JSpinner spTimeUpdate;
    private javax.swing.JTextField txtPort;
    // End of variables declaration//GEN-END:variables
    private GiaVang url;
    private ThreadCapNhat threadCapNhat;
    private UDPSC server;
}
